<?php
include_once('../config.php');
include_once('class.savedSearch.php');
include_once('misc.php');

header('Content-type: application/json');
header('charset: utf-8');

$savedSearch = new SavedSearch();
$valid = true;

switch(trim($_REQUEST['cmd'])) {
	case 'listSavedSearch':
		$timeStart = microtime(true);
		if($_REQUEST['sort'] != '') {
			$filter['order'] = array(array('field' => $_REQUEST['sort'], 'dir' => $_REQUEST['dir']));
		}
		$filter['assocFlag'] = trim($_REQUEST['assocFlag']);
		$filter['start'] = (trim($_REQUEST['start']) == '') ? 0 : trim($_REQUEST['start']);
		$filter['limit'] = (trim($_REQUEST['limit']) == '') ? 100 : trim($_REQUEST['limit']);
		$filter['searchType'] = trim($_REQUEST['searchType']);
		$filter['query'] = trim($_REQUEST['query']);
		$filter['type'] = (in_array(trim($_REQUEST['type']),array('exactMatch','startsWith'))) ? trim($_REQUEST['type']) : 'exactMatch';
		$records = $savedSearch->listSavedSearch($filter);
		$records = is_null($records) ? array() : $records;
		$output = array('success' => true, 'processTime' => (microtime(true) - $timeStart), 'recordCount' => $savedSearch->db->query_total(), 'records' => $records);
		print json_encode( $output );
		break;
	case 'listAssociation':
		$timeStart = microtime(true);
		$filter['term'] = trim($_REQUEST['term']);
		$filter['association'] = trim($_REQUEST['association']);
		$records = $savedSearch->listAssociation($filter);
		$records = is_null($records) ? array() : $records;
		print(json_encode(array('success' => true, 'processTime' => (microtime(true) - $timeStart), 'recordCount' => $savedSearch->db->query_total(), 'records' => $records)));
		break;
	case 'addAssociation':
		if(trim($_REQUEST['term']) == '') {
			$valid = false;
			$code = 101;
		}
		if(trim($_REQUEST['association']) == '') {
			$valid = false;
			$code = 102;
		}
		if($valid) {
			$savedSearch->set('term',trim($_REQUEST['term']));
			$savedSearch->set('association',trim($_REQUEST['association']));
			$savedSearch->addAssociation();
			print json_encode( array( 'success' => true ) );
		} else {
			print json_encode( array( 'success' => false, 'error' => array( 'msg' => getError($code), 'code' => $code ) ) );
		}
		break;
	case 'deleteAssociation':
		if(trim($_REQUEST['term']) == '') {
			$valid = false;
			$code = 101;
		}
		if(trim($_REQUEST['association']) == '') {
			$valid = false;
			$code = 102;
		}
		if($valid) {
			$savedSearch->set('term',trim($_REQUEST['term']));
			$savedSearch->set('association',trim($_REQUEST['association']));
			$savedSearch->deleteAssociation();
			print json_encode( array( 'success' => true ) );
		} else {
			print json_encode( array( 'success' => false, 'error' => array( 'msg' => getError($code), 'code' => $code ) ) );
		}
		break;
	default:
		print 'No Command Given';
		break;
}



?>